package com.gitee.base.security.shiro;


import com.gitee.base.utils.Kit;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class ShiroFilter extends AccessControlFilter {
    private final static Logger logger = LoggerFactory.getLogger(ShiroFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = Kit.getCookieToken((HttpServletRequest)servletRequest);
        if(StringUtils.isBlank(token)){
            redirectToLogin(servletRequest,servletResponse);
            return false;
        }
        try{
            getSubject(servletRequest,servletResponse).login(new ShiroToken(token));
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return onLoginFailure(token, e, servletRequest, servletResponse);
        }
        return true;
    }

    private boolean onLoginFailure(String token, Exception e, ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        redirectToLogin(servletRequest,servletResponse);
        return false;
    }
}
